﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Moq;
using System.IO;

namespace mscook.test
{
    public class MockHttpSession : HttpSessionStateBase
    {
        Dictionary<string, object> m_SessionStorage = new Dictionary<string, object>();

        public override object this[string name]
        {
            get { 
                     if(m_SessionStorage.ContainsKey(name))
                     {
                        return m_SessionStorage[name];
                     }
                     return null;
            }
            set { m_SessionStorage[name] = value; }
        }
    }
    public static class MvcMockHelpers
    {
        private static string ORIGIN_IMAGE_FOLDER = "ImageSettingFactoryTest";
        private static  string IMAGE_TO_BE_HANDLED = "1170X384.jpg";
        //public static HttpContextBase FakeHttpContext(MemoryStream ms)
        //{
        //    var context = new Mock<HttpContextBase>();
        //    var request = new Mock<HttpRequestBase>();
        //    var response = new Mock<HttpResponseBase>();
        //    var session = new MockHttpSession();
        //    var server = new Mock<HttpServerUtilityBase>();
        //    var user = new Mock<IPrincipal>();
        //    var identity=new Mock<IIdentity>();

        //    context.Setup(ctx => ctx.Request).Returns(request.Object);
        //    context.Setup(ctx => ctx.Response).Returns(response.Object);
        //    context.Setup(ctx => ctx.Session).Returns(session);
        //    context.Setup(ctx => ctx.Server).Returns(server.Object);
        //    context.Setup(ctx => ctx.User).Returns(user.Object);
        //    context.Setup(ctx => ctx.User.Identity).Returns(identity.Object);
        //    context.Setup(ctx => ctx.User.Identity.IsAuthenticated).Returns(true);
        //     var collection=new  Mock<HttpFileCollectionBase>();
        //    var file = new Mock<HttpPostedFileBase>();
        //        file.Setup(f => f.InputStream).Returns(ms);
        //        file.Setup(f => f.FileName).Returns("unname");
        //        collection.Setup(c => c.Get(It.IsAny<int>())).Returns(file.Object);
        //        request.Setup(req => req.Files).Returns(collection.Object);
            
             
        //    return context.Object;
        //}
        public static HttpContextBase FakeHttpContext()
        {
            var context = new Mock<HttpContextBase>();
            var request = new Mock<HttpRequestBase>();
            var response = new Mock<HttpResponseBase>();
            var session = new MockHttpSession();
            var server = new Mock<HttpServerUtilityBase>();
            var user = new Mock<IPrincipal>();
            var identity = new Mock<IIdentity>();

            context.Setup(ctx => ctx.Request).Returns(request.Object);
            context.Setup(ctx => ctx.Response).Returns(response.Object);
            context.Setup(ctx => ctx.Session).Returns(session);
            context.Setup(ctx => ctx.Server).Returns(server.Object);
            context.Setup(ctx => ctx.User).Returns(user.Object);
            context.Setup(ctx => ctx.User.Identity).Returns(identity.Object);
            context.Setup(ctx => ctx.User.Identity.IsAuthenticated).Returns(true);



            return context.Object;
        }
        public static HttpContextBase FakeHttpContext(string url)
        {
            HttpContextBase context = FakeHttpContext();
            context.Request.SetupRequestUrl(url);
            return context;
        }
        public static HttpContextBase FakeHttpContext(HttpFileCollectionBase files)
        {
            HttpContextBase context = FakeHttpContext();
            context.Request.SetupRequestFile(files);
            return context;
        }
        public static void SetFakeControllerContext(this Controller controller)
        {
            var httpContext = FakeHttpContext();
            ControllerContext context = new ControllerContext(new RequestContext(httpContext, new RouteData()), controller);
            controller.ControllerContext = context;
        }
        public static void SetFakeControllerContextAndUrlHelper(this Controller controller)
        {
            var httpContext = FakeHttpContext();
            ControllerContext context = new ControllerContext(new RequestContext(httpContext, new RouteData()), controller);
            controller.ControllerContext = context;
            var requestContext = new RequestContext(httpContext, new RouteData());
            controller.Url = new UrlHelper(requestContext, RouteTable.Routes);
        }
        public static void SetFakeControllerContext(this Controller controller, HttpFileCollectionBase files)
        {
            var httpContext = FakeHttpContext(files);
            ControllerContext context = new ControllerContext(new RequestContext(httpContext, new RouteData()), controller);
            controller.ControllerContext = context;
        }

        static string GetUrlFileName(string url)
        {
            if (url.Contains("?"))
                return url.Substring(0, url.IndexOf("?"));
            else
                return url;
        }

        static NameValueCollection GetQueryStringParameters(string url)
        {
            if (url.Contains("?"))
            {
                NameValueCollection parameters = new NameValueCollection();

                string[] parts = url.Split("?".ToCharArray());
                string[] keys = parts[1].Split("&".ToCharArray());

                foreach (string key in keys)
                {
                    string[] part = key.Split("=".ToCharArray());
                    parameters.Add(part[0], part[1]);
                }

                return parameters;
            }
            else
            {
                return null;
            }
        }

        public static void SetHttpMethodResult(this HttpRequestBase request, string httpMethod)
        {
            Mock.Get(request)
                .Setup(req => req.HttpMethod)
                .Returns(httpMethod);
        }

        public static void SetupRequestUrl(this HttpRequestBase request, string url)
        {
            if (url == null)
                throw new ArgumentNullException("url");

            if (!url.StartsWith("~/"))
                throw new ArgumentException("Sorry, we expect a virtual url starting with \"~/\".");

            var mock = Mock.Get(request);

            mock.Setup(req => req.QueryString)
                .Returns(GetQueryStringParameters(url));
            mock.Setup(req => req.AppRelativeCurrentExecutionFilePath)
                .Returns(GetUrlFileName(url));
            mock.Setup(req => req.PathInfo)
                .Returns(string.Empty);
        }
        public static void SetupRequestFile(this HttpRequestBase request, HttpFileCollectionBase files)
        {
            var mock = Mock.Get(request);
            mock.Setup(req => req.Files)
                .Returns(files);
        }
    }


}
